package com.hotacorp.opencloud.common.resourcecommon.config;

import java.io.IOException;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import com.hotacorp.opencloud.common.commdata.PermitUrlProperties;
import com.hotacorp.opencloud.common.resourcecommon.exception.CustomErrorController;
import com.hotacorp.opencloud.common.resourcecommon.exception.ExceptionHandlerAdvice;

/**
 * 资源服务器配置类，由EnableOpenCloudResourceServer注解导入
 * 资源服务器通过url获取授权服务器关于授权token信息，而不是通过redis或数据库方式共享token
 * @author lwg
 *
 */
@Configuration
@EnableWebSecurity
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(PermitUrlProperties.class)
@Import({CustomErrorController.class, ExceptionHandlerAdvice.class})
public class OpenCloudResourceServerConfiguration {

	/**
	 * 设置访问授权服务器方式为服务名方式，以便可以通过负载均衡方式获得授权信息
	 * @return
	 */
	@Bean("tokenInfoRestTemplate")
    @LoadBalanced
    public RestTemplate restTemplate() {
		HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
		//60s
		requestFactory.setConnectTimeout(60000);
		requestFactory.setReadTimeout(60000);
		
		RestTemplate restTemplate = new RestTemplate(requestFactory);
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			// Ignore 400
			public void handleError(ClientHttpResponse response) throws IOException {
				if (response.getRawStatusCode() != 400) {
					super.handleError(response);
				}
			}
		});
		return restTemplate;
    }

	@Bean
	public OpenCloudResourceServerConfigurerAdapter openCloudResourceServerConfigurerAdapter() {
		return new OpenCloudResourceServerConfigurerAdapter();
	}
	
}
